﻿/*
 * Copyright 2022 LookerSong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import router from '@system.router';
import images from '../../common/images.js';

var grids;
var context;
var timer;

var ctx0;   //参照画布，可替换

var CUT_SID = 85;
var SIDELEN = 55;
var MARGIN = 4;

export default {
    data: {
        block: 4,
        index: 0,
        img: new Image(),
        currentSeconds: 0,
        tip: false,
        isShow: false,
    },

    //网格初始化
    onInit() {
        CUT_SID = 360 / this.block - (this.block + 1);
        SIDELEN = 240 / this.block - (this.block + 1);
        MARGIN = this.block;
        this.img.src = images[this.index % images.length].src;
    },

    //页面显示
    onShow() {
        if(4 == this.block) {
            grids=[[1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 0]];
        }
        else {
            grids=[[1, 2, 3, 4, 5],
            [6, 7, 8, 9, 10],
            [11, 12, 13, 14, 15],
            [16, 17, 18, 19, 20],
            [21, 22, 23, 24, 0]];
        }
        timer = null;
        this.initGrids();
        this.drawGrids();
        timer = setInterval(this.run, 1000);
        this.refer();       //参照画布，可替换
    },

    //参照画布，可替换
    refer() {
        ctx0 = this.$refs.canvas0.getContext('2d');
        var init = new Image();
        init.src = this.img.src
        init.onload = function () {
            console.log('Image load success');
            ctx0.drawImage(init, 0, 0, 360, 360, 0, 0, 240, 240);

            //尝试获取图片的宽高，无效……
//            console.info(JSON.stringify(init));
//            console.info("参照图——宽：" + init.width + ",高：" + init.height);
        };
    },

    //随机上下左右打乱1000次
    initGrids() {
        let array=["left","up","right","down"];
        for (let i = 0; i < 1000; i++){
            let randomIndex = Math.floor(Math.random() * this.block);
            let direction = array[randomIndex];
            this.changeGrids(direction);
        }
    },

    //画网格
    drawGrids() {
        context = this.$refs.canvas.getContext('2d');
        for (let row = 0; row < this.block; row++) {
            for (let column = 0; column < this.block; column++) {
                let gridStr = grids[row][column].toString();
                context.fillStyle = "#BBADA0";
                let leftTopX = column * (MARGIN + SIDELEN) + MARGIN;
                let leftTopY = row * (MARGIN + SIDELEN) + MARGIN;
                context.fillRect(leftTopX, leftTopY, SIDELEN, SIDELEN);
                context.font = "28px HYQiHei-65S";
                if (gridStr != "0") {
                    context.fillStyle = "#000000";
                    let offsetX = (3 - gridStr.length) * (SIDELEN / 8);
                    let offsetY = (SIDELEN - 14);
                    context.drawImage(this.img,
                        (CUT_SID + MARGIN) * ((grids[row][column] - 1) % this.block) + MARGIN, //原图img的X轴裁剪起点
                        (CUT_SID + MARGIN) * (Math.floor((grids[row][column] - 1) / this.block)) + MARGIN, //原图img的Y轴裁剪起点
                        CUT_SID, CUT_SID, //原图X轴，Y轴方向的裁剪长度
                        leftTopX, leftTopY, //画布X轴，Y轴画图的起点
                        SIDELEN, SIDELEN); //画布X轴，Y轴画图的长度
//                    console.info(JSON.stringify(this.img));
//                    console.info("拼图——宽：" + this.img.width + ",高：" + this.img.height);
                    if(true == this.tip) {
                        context.fillText(gridStr, leftTopX + offsetX, leftTopY + offsetY);
                    }
                    else {
                        context.fillText("", leftTopX + offsetX, leftTopY + offsetY);
                    }
                }
                else {
                    if(true == this.isShow) {
                        context.drawImage(this.img,
                            (CUT_SID + MARGIN) * ((Math.pow(this.block, 2) - 1) % this.block) + MARGIN, //原图img的X轴裁剪起点
                            (CUT_SID + MARGIN) * (Math.floor((Math.pow(this.block, 2) - 1) / this.block)) + MARGIN, //原图img的Y轴裁剪起点
                            CUT_SID, CUT_SID, //原图X轴，Y轴方向的裁剪长度
                            leftTopX, leftTopY, //画布X轴，Y轴画图的起点
                            SIDELEN, SIDELEN); //画布X轴，Y轴画图的长度
                    }
                    else {
                        context.drawImage(this.img, 0, 0, 0, 0, 0, 0, SIDELEN, SIDELEN);
                    }
                }
            }
        }
    },

    //计时显示，小数点后一位
    run(){
        this.currentSeconds += 1;
    },

    //滑动网格
    swipeGrids(event) {
        this.changeGrids(event.direction);

        if(this.gameover()){
            clearInterval(timer);
            this.isShow = true;
            this.tip = false;
        }
        this.drawGrids();
    },

    //游戏结束判断
    gameover(){
        let originalgrids;

        if(4 == this.block) {
            originalgrids=[[1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 0]];
        }
        else {
            originalgrids=[[1, 2, 3, 4, 5],
            [6, 7, 8, 9, 10],
            [11, 12, 13, 14, 15],
            [16, 17, 18, 19, 20],
            [21, 22, 23, 24, 0]];
        }

        for (let row = 0; row < this.block; row++) {
            for (let column = 0; column < this.block; column++) {
                if (grids[row][column] != originalgrids[row][column]){
                    return false;
                }
            }
        }
        return true;
    },

    //滑动操作
    changeGrids(direction) {
        let x;
        let y;
        for (let row = 0; row < this.block; row++) {
            for (let column = 0; column < this.block; column++) {
                if (grids[row][column] == 0) {
                    x = row;
                    y = column;
                    break;
                }
            }
        }
        let temp;
        if(this.isShow==false){
            if (direction == 'left' && (y + 1) < this.block) {
                temp = grids[x][y + 1];
                grids[x][y + 1] = grids[x][y];
                grids[x][y] = temp;
            } else if (direction == 'right' && (y - 1) > -1) {
                temp = grids[x][y - 1];
                grids[x][y - 1] = grids[x][y];
                grids[x][y] = temp;
            } else if (direction == 'up' && (x + 1) < this.block) {
                temp = grids[x + 1][y];
                grids[x + 1][y] = grids[x][y];
                grids[x][y] = temp;
            } else if (direction == 'down' && (x - 1) > -1) {
                temp = grids[x - 1][y];
                grids[x - 1][y] = grids[x][y];
                grids[x][y] = temp;
            }
        }
    },

    //重新开始
    restartGame(){
        this.tip = false;
        clearInterval(timer);
        this.currentSeconds = 0;
        this.isShow = false;

        this.onShow();
    },

    //数字提示开关
    gethelp() {
        this.tip = !this.tip;
        this.drawGrids();
    },

    //换张图
    changeimage() {
        this.index += 1;
        this.img.src = images[this.index % images.length].src;

        this.restartGame();
    },

    //回到首页
    quit() {
        router.replace({
            uri: "pages/index/index"
        })
    }
}